import SwiftUI
import PhotosUI
import Alamofire

struct Sell_Picker: UIViewControllerRepresentable {
    @Environment(\.dismiss) var dismiss
    
    @Binding var imageIdArray: [String]
    
    var bookId: String
    
    func makeUIViewController(context: UIViewControllerRepresentableContext<Sell_Picker>) -> PHPickerViewController {
        var configuration = PHPickerConfiguration(photoLibrary: PHPhotoLibrary.shared())
        configuration.filter = .images
        configuration.preferredAssetRepresentationMode = .current

        let photoPickerViewController = PHPickerViewController(configuration: configuration)
        photoPickerViewController.delegate = context.coordinator
        return photoPickerViewController
    }
    
    func makeCoordinator() -> Sell_Coordinator {
        Sell_Coordinator(self)
    }

    func updateUIViewController(_ uiViewController: PHPickerViewController, context: UIViewControllerRepresentableContext<Sell_Picker>) {
    }
}

struct ResponseData_UploadImage: Codable {
    let status: Bool
    let description: String
    let imageId: String
}

class Sell_Coordinator: NSObject, UINavigationControllerDelegate, PHPickerViewControllerDelegate {
    let parent: Sell_Picker
    
    func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {
        self.parent.dismiss()
        
        guard
            let result = results.first,
            result.itemProvider.hasItemConformingToTypeIdentifier(UTType.image.identifier)
        else { return }
        
        result.itemProvider.loadFileRepresentation(forTypeIdentifier: UTType.image.identifier) { url, error in
            if let error = error {
                print("Error loading file representation: \(error.localizedDescription)")
            } else if let url = url {
                // 获取图片文件
                let imageData : Data = try! Data.init(contentsOf: url)
                let image : UIImage = UIImage(data: imageData)!
                
                // 压缩
                let targetSize = 2 * 1024 * 1024
                var compression = 0.9
                var compressImage = image.jpegData(compressionQuality: compression)!
                while (compressImage.count > targetSize && compression > 0.1) {
                    compression -= 0.1;
                    compressImage = image.jpegData(compressionQuality: compression)!
                }
                
                // 上传
                let requestURL = "http://62.234.45.120:1230/Book/uploadImage?bookId=" + self.parent.bookId
                AF.upload(multipartFormData: { multipartFormData in
                    multipartFormData.append(compressImage, withName: "bookImage", fileName: self.parent.bookId + ".jpeg", mimeType: "image/jpeg")
                    }, to: requestURL)
                .responseDecodable(of: ResponseData_UploadImage.self){ response in
                    if let responseData = response.value {
                        if responseData.status {
                            self.parent.imageIdArray.append(responseData.imageId)
                        }
                    }
                }
            }
        }
    }
    
    init(_ parent: Sell_Picker) {
        self.parent = parent
    }
}
